import 'package:chat/common/utils/storage.dart';
import 'package:dio/dio.dart' as dio;
import 'package:get/get.dart';

/// 网络请求工具类
class HttpService extends GetxService {
  static HttpService get to => Get.find();

  late dio.Dio _dio;

  // 基础 URL，可以根据需要改
  final String baseUrl = "http://172.20.10.4:2025/api";

  @override
  void onInit() {
    super.onInit();
    _initDio();
  }

  void _initDio() {
    _dio = dio.Dio(
      dio.BaseOptions(
        baseUrl: baseUrl,
        connectTimeout: const Duration(seconds: 10),
        receiveTimeout: const Duration(seconds: 10),
        headers: {"Content-Type": "application/json"},
      ),
    );

    // 添加拦截器
    _dio.interceptors.add(
      dio.InterceptorsWrapper(
        onRequest: (options, handler) {
          // 请求前加access_token
          final token = Storage().getAccessToken();
          if (token.isNotEmpty) {
            options.headers["Authorization"] = "Bearer $token";
          }
          print("👉 Request[${options.method}] => PATH: ${options.path}");
          return handler.next(options);
        },
        onResponse: (response, handler) {
          print("✅ Response[${response.statusCode}] => PATH: ${response.requestOptions.path}");
          return handler.next(response);
        },
        onError: (dio.DioException e, handler) async {
          print("❌ DioError[${e.response?.statusCode}] => ${e.message}");

          // 处理 Token 失效，比如 401
          if (e.response?.statusCode == 401) {
            bool success = await _refreshToken();
            if (success) {
              // 刷新成功 → 重新请求
              final retryResponse = await _retryRequest(e.requestOptions);
              return handler.resolve(retryResponse);
            } else {
              // 刷新失败 → 清空缓存，跳登录
              await Storage().remove(Storage.ACCESS_TOKEN);
              await Storage().remove(Storage.REFRESH_TOKEN);
              Get.offAllNamed("/login");
            }
          }

          return handler.next(e);
        },
      ),
    );
  }

  /// 统一 GET
  Future<dio.Response> get(String path, {Map<String, dynamic>? query}) => _dio.get(path, queryParameters: query);

  /// 统一 POST
  Future<dio.Response> post(String path, {Map<String, dynamic>? query, dynamic data}) => _dio.post(path, queryParameters: query, data: data);

  /// 统一PUT
  Future<dio.Response> put(String path, {Map<String, dynamic>? query, dynamic data}) => _dio.put(path, queryParameters: query, data: data);

  /// 统一DELETE
  Future<dio.Response> delete(String path, {Map<String, dynamic>? query}) => _dio.delete(path, queryParameters: query);

  /// 刷新 Token
  Future<bool> _refreshToken() async {
    final refreshToken = await Storage().getRefreshToken();
    if (refreshToken.isEmpty) return false;

    try {
      final response = await HttpService.to.post("/auth/refresh", data: {"refresh_token": refreshToken});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final newAccessToken = response.data["data"]["access_token"];
        await Storage().setAccessToken(newAccessToken);
        print("✅ Token 刷新成功");
        return true;
      } else {
        print("❌ Token 刷新失败，需重新登录");
      }
    } catch (e) {
      print("刷新 token 异常: $e");
    }
    return false;
  }

  /// 失败请求重试
  Future<dio.Response> _retryRequest(dio.RequestOptions requestOptions) async {
    final options = dio.Options(method: requestOptions.method, headers: requestOptions.headers);
    return _dio.request(requestOptions.path, data: requestOptions.data, queryParameters: requestOptions.queryParameters, options: options);
  }
}
